<template>
  <div class="telBook">
    <div class="telBook-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-telbookadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button type="primary" v-btnpermission="'btn-telbookload'"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="活动名称" prop="activityName">
            <el-select
              v-model="formSearch.activityName"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in activityDic"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formSearch.name" />
          </el-form-item>
          <el-form-item label="城市" prop="cityCode">
            <el-tree-select
              v-model="formSearch.cityCode"
              :data="cityTreeOption"
              :props="defaultProps"
              node-key="Code"
              @change="onChange"
              check-strictly
            />
          </el-form-item>
          <!-- <el-form-item label="分组" prop="blockcoding">
            <el-select
              v-model="formSearch.blockcoding"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in blockDic"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="telBook-list">
      <el-row>
        <el-col>
          <!-- 电话簿列表 -->
          <el-table :data="telBookList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column prop="Name" label="姓名"></el-table-column>
            <!-- <el-table-column
              prop="BlockName"
              label="所属分组"
            ></el-table-column> -->
            <el-table-column prop="CityName" label="所属城市"></el-table-column>
            <el-table-column
              prop="Telephone"
              label="联系方式"
            ></el-table-column>
            <el-table-column label="是否有效">
              <template #default="scope">
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  v-model="scope.row.IsValid"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="Remarks" label="备注"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-telbookupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-telbookdelete'"
                  @click="DeleteDialog(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        title="添加通讯录"
        v-model="addDialogVisible"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogform"
          ref="addDialogRef"
          :rules="telbookFormRulesMixin.addFormRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="姓名" prop="Name">
                <el-input v-model="addDialogform.Name" /> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="城市">
                <el-tree-select
                  v-model="addDialogform.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  node-key="Code"
                  @change="onChange"
                  check-strictly
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="分组" prop="BlockCoding">
                <el-select
                  v-model="addDialogform.BlockCoding"
                  placeholder="--请选择--"
                >
                  <el-option
                    v-for="item in blockDic"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="联系方式" prop="Telephone">
                <el-input v-model="addDialogform.Telephone" /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="IsValid">
                <el-checkbox
                  v-model="addDialogform.IsValid"
                  size="large"
                  label="是否有效"
                  :true-label="1"
                  :false-label="0"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="备注" prop="Remarks">
                <el-input
                  v-model="addDialogform.Remarks"
                  :rows="3"
                  type="textarea"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button
              color="#8172D5"
              style="color: white"
              @click="addFormSubmit"
              >确定</el-button
            >
            <el-button color="#8172D5" plain @click="addDialogVisible = false"
              >取消</el-button
            >
          </span>
        </template>
      </el-dialog>
      <el-dialog
        title="修改通讯录"
        v-model="editDialogVisible"
        @close="editDislogClosed"
      >
        <el-form
          :model="editDialogform"
          ref="editDialogRef"
          label-width="120px"
          :rules="telbookFormRulesMixin.editFormRules"
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="姓名" prop="Name">
                <el-input v-model="editDialogform.Name" /> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="城市">
                <el-tree-select
                  v-model="editDialogform.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  node-key="Code"
                  @change="onChange"
                  check-strictly
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="分组" prop="BlockCoding">
                <el-select
                  v-model="editDialogform.BlockCoding"
                  placeholder="--请选择--"
                >
                  <el-option
                    v-for="item in blockDic"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="联系方式" prop="Telephone">
                <el-input v-model="editDialogform.Telephone" /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="IsValid">
                <el-checkbox
                  v-model="editDialogform.IsValid"
                  size="large"
                  label="是否有效"
                  :true-label="1"
                  :false-label="0"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="备注" prop="Remarks">
                <el-input
                  v-model="editDialogform.Remarks"
                  :rows="3"
                  type="textarea"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button
              color="#8172D5"
              style="color: white"
              @click="editFormSubmit"
              >确定</el-button
            >
            <el-button color="#8172D5" plain @click="editDialogVisible = false"
              >取消</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { getDicByTableName, getCityTree } from '@/network/dictionary.js';
import { Edit, Delete } from '@element-plus/icons-vue';
import { telbookFormRulesMixin } from '@/utils/mixin.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getTelBookList,
  addTelBook,
  editTelBook,
  deleteTelBook,
  addTelBookList,
} from '@/network/telBook';
import { importExcel } from '@/utils/excel';
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
let blocklist;
let onChange = async (val) => {
  blockDic.value = blocklist.filter((it) => it.CityCode == val);
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addTelBookList(res).then(() => {
        ElMessage.success('导入成功');
        initDic();
        initData();
      });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
//查询
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
let activityDic = ref([]);
let cityTreeOption = ref([]);
let blockDic = ref([]);
const addDialogVisible = ref(false);
const formSearch = reactive({
  activityName: '',
  name: '',
  cityCode: '',
  blockcoding: '',
  total: 0,
  pageSize: 10,
  page: 1,
});
//搜索
const onSubmit = () => {
  formSearch.page = 1;
  initData();
};
//重置
const onReset = () => {
  formSearch.activityName = '';
  formSearch.name = '';
  formSearch.cityCode = '';
  formSearch.blockcoding = '';
  formSearch.total = 0;
  formSearch.pageSize = 10;
  formSearch.page = 1;
  initData();
};
const handleCurrentChange = (val) => {
  formSearch.page = val;
  initData();
};
//#region 新增数据
const addDialogRef = ref(null);
const addDialogform = ref({
  Code: 0,
  Name: '',
  BlockCoding: null,
  Telephone: '',
  Remarks: '',
  IsValid: 1,
  CityCode: null,
});
const addDislogClosed = () => {
  addDialogVisible.value = false;
  addDialogform.value = {};
};
//表单验证
const addFormSubmit = () => {
  addDialogRef.value.validate(async (valid) => {
    if (valid) {
      await addTelBook(addDialogform.value)
        .then(() => {
          addDialogVisible.value = false;
          initData();
          ElMessage.success('添加成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.warning('添加失败！');
        });
    } else {
      ElMessage.error('请填写必要的必填项！');
      return false;
    }
  });
};
//#endregion
//#region 删除数据
const DeleteDialog = (id) => {
  ElMessageBox.confirm('确定删除吗?', '提示', {
    type: 'warning',
  })
    .then(async () => {
      await deleteTelBook({ code: id })
        .then(() => {
          initData();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.warning('删除失败！');
        });
    })
    .catch(() => {
      console.log('取消');
    });
};
//#endregion
//#region 编辑数据
const editDialogRef = ref(null);
let editDialogform = ref({
  Code: 0,
  Name: '',
  BlockCoding: null,
  Telephone: '',
  Remarks: '',
  IsValid: 1,
  CityCode: null,
});
let editDialogVisible = ref(false);
const editDislogClosed = () => {
  editDialogVisible.value = false;
  editDialogform.value = {};
};
//表单验证
const editFormSubmit = () => {
  editDialogRef.value.validate(async (valid) => {
    if (valid) {
      await editTelBook(editDialogform.value)
        .then(() => {
          editDialogVisible.value = false;
          initData();
          ElMessage.success('编辑成功');
        })
        .catch((err) => {
          ElMessage.warning('编辑失败！');
          console.log(err);
        });
    } else {
      ElMessage.error('请填写必要的必填项！');
      return false;
    }
  });
};
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  // editDialogform.code = row.code;
  // editDialogform.name = row.name;
  // editDialogform.blockcoding = row.blockcoding;
  // editDialogform.telephone = row.telephone;
  // editDialogform.remarks = row.remarks;
  // editDialogform.invalid = row.invalid;
  editDialogform.value = JSON.parse(JSON.stringify(row));
};
//#endregion
let telBookList = ref(null);
const initData = async () => {
  let data = {
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    activityName: formSearch.activityName,
    name: formSearch.name,
    cityCode: formSearch.cityCode,
    blockcoding: formSearch.blockcoding,
  };
  await getTelBookList(data)
    .then((result) => {
      telBookList.value = result.data;
      formSearch.total = result.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
//初始化字典数据
const initDic = async () => {
  await getDicByTableName({ tableName: 'tactivity' })
    .then((result) => {
      activityDic.value = result;
    })
    .catch((err) => {
      console.log(err);
    });
  //获取城市
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  await getDicByTableName({ tableName: 'tblockcoding' })
    .then((result) => {
      blockDic.value = result;
      blocklist = result;
    })
    .catch((err) => {
      console.log(err);
    });
};
onMounted(() => {
  initDic().then(() => {
    initData();
  });
});
</script>

<style lang="scss" scoped>
.telBook {
  margin: 14px 15px 14px;
  .telBook-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .telBook-list {
    margin-top: 14px;
  }
}
</style>
